package com.xinyue.game.gateway.server;

import com.xinyue.game.gateway.server.socket.SocketServerChannelInitializer;
import com.xinyue.game.gateway.server.websocket.WebSocketServerChannelInitializer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * @author 王广帅
 * @date 2021年01月26日 7:55 下午
 */

public class GameServerBoot {

    private static Logger logger = LoggerFactory.getLogger(GameServerBoot.class);
    private static GameNetworkServer networkServer;

    /**
     * 启动服务，使用socket的方式与客户端进行通信
     *
     * @param context
     */
    public static void startSocketServer(ApplicationContext context) {
        SocketServerChannelInitializer channelInitializer = new SocketServerChannelInitializer(context);
        startServer(channelInitializer, context);
    }

    /**
     * 启动服务，使用websocket的方式与客户端进行通信
     *
     * @param context
     */
    public static void startWebSocketServer(ApplicationContext context) {
        WebSocketServerChannelInitializer channelInitializer = new WebSocketServerChannelInitializer(context);
        startServer(channelInitializer, context);
    }

    private static void startServer(ChannelInitializer<Channel> channelInitializer, ApplicationContext context) {
        //启动Netty服务端监听
        networkServer = new GameNetworkServer(context);
        Thread nt = new Thread(() -> {
            networkServer.start(channelInitializer);
        });
        nt.start();
    }

    public static void stop() {
        logger.info("--->服务器开始关闭");
        networkServer.stop();
        logger.info("--->服务器关闭成功");
    }
}
